package com.young.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.young.domain.SysUser;
import com.young.domain.SysUserExample;
import com.young.domain.SysUserExample.Criteria;
import com.young.domain.SysUserRole;
import com.young.mapper.SysUserMapper;
import com.young.mapper.SysUserRoleMapper;
import com.young.req.AddUserReq;
import com.young.req.SysUserPageReq;
import com.young.shop.service.SysUserService;
import java.util.Date;
import java.util.List;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 用户相关服务类
 * @Author: kangyang
 * @Date: 2021/5/12 10:11
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

  private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

  @Autowired(required = false)
  private SysUserMapper sysUserMapper;

  @Autowired(required = false)
  private SysUserRoleMapper sysUserRoleMapper;

  @Override
  public SysUser getUserByUserName(String username) {
    SysUserExample sysUserExample = new SysUserExample();
    Criteria criteria = sysUserExample.createCriteria();
    criteria.andUsernameEqualTo(username);
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
    if(CollectionUtils.isEmpty(sysUsers) || sysUsers.size() > 1) {
      return null;
    }
    return sysUsers.get(0);
  }

  @Override
  public PageInfo<SysUser> getSysUserPage(SysUserPageReq sysUserPageReq) {
    PageInfo<SysUser> sysUserPage = new PageInfo<>();
    if(sysUserPageReq == null) {
      return sysUserPage;
    }
    PageHelper.startPage(sysUserPageReq.getCurrent(), sysUserPageReq.getSize());
    SysUserExample sysUserExample = new SysUserExample();
    Criteria criteria = sysUserExample.createCriteria();
    criteria.andIsDeleteEqualTo(Boolean.FALSE);
    if(StringUtils.isNotEmpty(sysUserPageReq.getUsername())) {
      criteria.andUsernameLike("%" + sysUserPageReq.getUsername() + "%");
    }
    sysUserExample.setOrderByClause("update_time");
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
    sysUserPage.setList(sysUsers);
    return sysUserPage;
  }

  @Override
  public SysUser getUserByUserId(Long userId) {
    SysUserExample sysUserExample = new SysUserExample();
    Criteria criteria = sysUserExample.createCriteria();
    criteria.andUserIdEqualTo(userId);
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
    if(CollectionUtils.isNotEmpty(sysUsers)) {
      return sysUsers.get(0);
    }
    return new SysUser();
  }

  @Override
  @Transactional
  public Boolean delectUserByUserIds(List<Long> userIds) {
    if(CollectionUtils.isNotEmpty(userIds)) {
      for (Long userId : userIds) {
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setUpdateTime(new Date());
        user.setIsDelete(Boolean.TRUE);
        sysUserMapper.updateByPrimaryKeySelective(user);
        sysUserRoleMapper.deleteByUserId(userId);
      }

    }
    return null;
  }

  @Override
  @Transactional
  public Boolean insertUser(AddUserReq addUserReq) {
    SysUser user = new SysUser();
    Date date = new Date();
    user.setUserId(date.getTime());
    user.setCreateTime(date);
    user.setUpdateTime(date);
    BeanUtils.copyProperties(addUserReq, user);
    if(StringUtils.isNotEmpty(addUserReq.getPassword())) {
      // 密码不为空需对密码加密处理
      Md5Hash md5Hash = new Md5Hash(addUserReq.getPassword(), ByteSource.Util.bytes("young".getBytes()), 2);
      String hex = md5Hash.toHex();
      user.setPassword(hex);
    }
    try {
      sysUserMapper.insert(user);
      List<Long> roleIdList = addUserReq.getRoleIdList();
      if (CollectionUtils.isNotEmpty(roleIdList)) {
        roleIdList.forEach(roleId -> {
          SysUserRole sysUserRole = new SysUserRole();
          sysUserRole.setRoleId(roleId);
          sysUserRole.setUserId(user.getUserId());
          sysUserRoleMapper.insert(sysUserRole);
        });
      }
    }catch (Exception e) {
      e.printStackTrace();
      return Boolean.TRUE;
    }
    return Boolean.FALSE;
  }

  @Override
  @Transactional
  public Boolean updateUser(AddUserReq addUserReq) {
    if(addUserReq == null) {
      return Boolean.FALSE;
    }
    Long userId = addUserReq.getUserId();
    SysUserExample sysUserExample = new SysUserExample();
    Criteria criteria = sysUserExample.createCriteria();
    criteria.andUserIdEqualTo(userId);
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
    if(CollectionUtils.isEmpty(sysUsers)) {
      log.warn("查询的用户为空");
      throw new AccountException("查询的用户为空");
    }
    SysUser user = new SysUser();
    BeanUtils.copyProperties(addUserReq, user);
    if(StringUtils.isNotEmpty(addUserReq.getPassword())) {
      // 密码不为空需对密码加密处理
      Md5Hash md5Hash = new Md5Hash(addUserReq.getPassword(), ByteSource.Util.bytes("young".getBytes()), 2);
      String hex = md5Hash.toHex();
      user.setPassword(hex);
    }
    sysUserMapper.updateByPrimaryKeySelective(user);
    List<Long> roleIdList = addUserReq.getRoleIdList();
    // 先删除用户与角色中间表
    sysUserRoleMapper.deleteByUserId(userId);
    if(CollectionUtils.isNotEmpty(roleIdList)) {
      roleIdList.forEach(roleId -> {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setId(new Date().getTime());
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(roleId);
        sysUserRole.setIsDelete(Boolean.FALSE);
        sysUserRoleMapper.insert(sysUserRole);
      });
    }

    return Boolean.TRUE;
  }
}
